import datetime
import json
import os
import re
from filecmp import dircmp
from shutil import copy, rmtree
from typing import List

import xlrd


def readexcel(type):
    '''
    读取excel 导出json
    '''
    print("...正在读取 "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    excelpath = os.path.join("./AMap_adcode_citycode_2020_07_27.xlsx")
    wb = xlrd.open_workbook(excelpath)
    ws = wb.sheet_by_index(0)

    arr = []

    for rowindex in range(1, ws.nrows):
        row = ws.row(rowindex)
        citycn = row[0]
        c_adcode = row[1]
        citycode = row[2]
        if c_adcode.value != '100000':
            arr.append({
                "citycn": citycn.value,  "adcode": c_adcode.value, "citycode": citycode.value
            })
    print("...读取完成 "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    new_arr = format_data(arr, type)
    # 转换json
    json_str = json.dumps(obj=new_arr, ensure_ascii=False, skipkeys=True)

    if type == 1:
        with open(file="./province.json", mode="w") as stream:
            stream.write(json_str)
    if type == 2:
        with open(file="./province_city.json", mode="w") as stream:
            stream.write(json_str)
    if type == 3:
        with open(file="./province_city_area.json", mode="w") as stream:
            stream.write(json_str)
    print("...写入完成 "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


def format_data(arr, type):
    arr_province = []
    for l in arr:
        if re.match(
                string=l['adcode'], pattern="[0-9]{2}[0]{4}") != None:
            arr_province.append({
                "citycn": l['citycn'],  "adcode": l['adcode'], "citycode": l['citycode'],
                "type": "province",
                "children": None if type <= 1 else get_city(arr, provincecode=l['adcode'], type=type)
            })
    return None if arr_province.__len__() == 0 else arr_province


def get_city(arr: List, provincecode: str, type):
    province_code = provincecode[0:2]

    arr_city = []
    for l in arr:
        # print(province_code+l['adcode'][2:4]+"00")
        if l['adcode'] != provincecode and re.match(string=l['adcode'], pattern=province_code+"[0-9]{2}[0]{2}") != None:

            arr_city.append({
                "citycn": l['citycn'],  "adcode": l['adcode'], "citycode": l['citycode'],
                "type": "city",
                "children": None if type <= 2 else get_area(arr, citycode=l['adcode'])
            })

# 增加地级市到市级目录
        elif l['adcode'] != provincecode and l['adcode'] != province_code+l['adcode'][2:4]+"00" and re.match(string=l['adcode'], pattern=province_code+"[0-9]{4}") != None and is_exit(arr, province_code+l['adcode'][2:4]+"00", "adcode") == False:
            arr_city.append({
                "citycn": l['citycn'],  "adcode": l['adcode'], "citycode": l['citycode'],
                "type": "city",
                "children": None
            })

    return None if arr_city.__len__() == 0 else arr_city


def get_area(arr, citycode: str):
    city_code = citycode[0:4]
    arr_area = []
    for l in arr:
        if citycode != l['adcode'] and re.match(string=l['adcode'], pattern=city_code+"\d{2}") != None:
            arr_area.append({
                "citycn": l['citycn'],  "adcode": l['adcode'], "citycode": l['citycode'], "type": "area",
            })
    return None if arr_area.__len__() == 0 else arr_area


def is_exit(arr: list, str: str, prop: str):
    for l in arr:
        if(l[prop] == str):
            return True

    return False


if __name__ == "__main__":

    print('---------------start----------------')
    readexcel(1)
    readexcel(2)
    readexcel(3)
    print('---------------end----------------')
